<template>
  <onez-view class="menu" v-if="menu" @click.native="click">
    <template v-if="menu.name">
      <onez-view class="name" :class="active ? 'active' : ''">{{ menu.name }}</onez-view>
    </template>
    <template v-if="menu.children && menu.children.length">
      <onez-menu v-for="(item, key) in menu.children" :target="target" :menu="item" :key="key"></onez-menu>
    </template>
  </onez-view>
</template>

<script>
	import onezView from '../onez-view/onez-view.vue'
export default {
  name: 'onez-menu',
  components: {
  	onezView
  },
  data() {
    return {
      menuKey: null,
      active: false
    };
  },
  props: {
    target:{
      type:String,
      default:null
    },
    menu: {
      type: Object,
      default: null
    }
  },
  mounted() {
    this.init();
    this.$game.$on('menu-change', this.onMenu);
  },
  destroyed() {
    this.$game.$off('menu-change', this.onMenu);
  },
  methods: {
    init() {
      if (this.menu) {
        if (this.menu.menuKey) {
          this.menuKey = this.menu.menuKey;
        } else if (this.menu.page) {
          this.menuKey = 'page:'+this.menu.page;
        }
        this.active = this.$game.menuKey == this.menuKey;
      }
    },
    onMenu(e) {
      this.active = this.$game.menuKey == this.menuKey;
    },
    click(e) {
      if (!this.menu) {
        return;
      }
      if (this.menu.event) {
        this.$game.onEvent(this, this.menu.event);
      } else if (this.menu.page) {
        this.$game.onEvent(this, {
          action: 'menu',
          target: this.target,
          page: this.menu.page
        });
      }
    }
  }
};
</script>

<style scoped>
.menu {
  margin:0 5px 5px 0;
}
.menu .name {
  width: 80px;
  border: 1px solid #015e88;
  color: #fff;
  text-align: center;
  padding: 5px 0;
  background: #1cb5cb;
  cursor: pointer;
  white-space: nowrap;
}
.menu .name.active {
  border: 1px solid #015e88;
  background: #0f91a9;
}
</style>
